<template>
  <section>
    <!-- 工具条 高级查询 -->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true">
        <el-form-item>
          <el-input v-model="keyword" placeholder="请输入关键字"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="keywordQuery">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表-->
    <el-table :data="petTypes" highlight-current-row v-loading="listLoading" @selection-change="selsChange"
              style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column prop="name" label="宠物类型名称" width="120" sortable>
      </el-table-column>
      <el-table-column prop="description" label="描述" width="100" sortable>
      </el-table-column>
      <el-table-column prop="parentId" label="父类型id" width="100" sortable>
      </el-table-column>
<!--      <el-table-column label="领养人" width="180">-->
<!--        <template scope="scope">-->
<!--          <span v-if="scope.row.user" style="color: orange">{{scope.row.user.username}}</span>-->
<!--          <span v-else style="color: blueviolet">暂无领养人</span>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="操作">
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">修改</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination @current-change="handleCurrentChange" layout="prev, pager, next"
                     background
                     :page-size="pageSize"
                     :total="totals"
                     :current-page="currentPage" style="float:right;">
      </el-pagination>
    </el-col>

    <!--添加或修改界面-->
    <el-dialog :title="title" :visible.sync="saveFormVisible" :close-on-click-modal="false">
      <el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
        <el-form-item label="宠物类型名称" prop="name">
          <el-input v-model="saveForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="saveForm.description" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="父类型id">
          <el-input v-model="saveForm.parentId" auto-complete="off"></el-input>
        </el-form-item>
<!--        <el-form-item label="宠物类型">-->
<!--          <el-cascader v-model="saveForm.typeId"-->
<!--                       :options="petTypeTree"-->
<!--                       :props="{-->
<!--                checkStrictly: true,-->
<!--                label: 'name',-->
<!--                value: 'id'-->
<!--              }"-->
<!--                       clearable>-->
<!--          </el-cascader>-->
<!--        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="saveFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">提交</el-button>
      </div>
    </el-dialog>

  </section>
</template>

<script>
export default {
  data() {
    return {
      //1.分页查询的相关参数
      petTypes: [],
      pageSize: 5,
      currentPage: 1,
      totals: 0,
      listLoading: false,

      //2.高级查询的相关参数
      keyword: "",
      //3.批量删除的相关数据
      sels: [],

      //4.添加或修改相关数据
      title: '',
      saveFormVisible: false,//对话框界面是否显示
      saveLoading: false,//保存的加载框
      saveFormRules: {
        name: [
          {required: true, message: '请输入宠物类型名称', trigger: 'blur'}
        ]
      },
      //添加或修改界面数据
      saveForm: {
        id: null,
        name: '',
        description: null,
        parentId: null
      },
      //显示宠物类型树
      petTypeTree: []
    }
  },
  methods: {
    //1.获取宠物列表
    getpetTypes() {
      let para = {
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        keyword: this.keyword
      };
      this.listLoading = true; //显示加载框
      this.$http.post("/petType", para).then(res => {
        this.petTypes = res.data.data;
        this.totals = res.data.totals;
        this.listLoading = false;
      }).catch(res => {
        this.$message.error("系统繁忙，请稍后重试!!!");
      })
    },
    //2.分页实现
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getpetTypes();
    },
    //3.高级查询实现
    keywordQuery() {
      this.currentPage = 1;
      this.getpetTypes();
    },
    //4.删除功能实现
    handleDel: function (index, row) {
      //elementUI提供的模态框 - 点击确认执行then里面的代码，取消执行catch
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        this.$http.delete("/petType/" + row.id).then(res => {
          this.listLoading = false;
          if (res.data.success) {
            this.$message.success("删除成功");
            //删除成功后对当前页的处理
            var totalPage = Math.ceil(this.totals/this.pageSize);//总页数-最后一页
            if(this.currentPage==totalPage && (this.totals-1)%this.pageSize==0 && this.currentPage!=1){
              this.currentPage--;
            }
            this.getpetTypes();
          } else {
            this.$message.error("系统繁忙，请稍后重试!!![500]")
          }
        }).catch(res => {
          this.$message.error("系统繁忙，请稍后重试!!![404]")
        })
      }).catch(() => {

      });
    },
    selsChange: function (sels) {
      this.sels = sels;
    },
    //5.批量删除
    batchRemove: function () {
      //获取数组中每一个对象的id 并形成新的数组
      var ids = this.sels.map(item => item.id);
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true; //显示加载框
        this.$http.patch("/petType", ids).then(res => {
          this.listLoading = false; //隐藏加载框
          if (res.data.success) { //操作成功
            this.$message.success("删除成功");
            var totalPage = Math.ceil(this.totals/this.pageSize);//总页数-最后一页
            if(this.currentPage==totalPage && (this.totals-ids.length)%this.pageSize==0 && this.currentPage!=1){
              this.currentPage--;
            }
            this.getpetTypes();
          } else { //操作失败
            this.$message.error("系统繁忙，请稍后重试!!![500]");
          }
        }).catch(res => {
          this.$message.error("系统繁忙，请稍后重试!!![400,404]");
        })
      }).catch(() => {

      });
    },
    //7.点击修改按钮弹出对话框
    handleEdit: function (index, row) {
      this.title = "修改";
      this.saveFormVisible = true;//弹出对话框
      //回显数据：创建一个空对象{}，将row中的数据拷贝给{}
      this.saveForm = Object.assign({}, row);
      this.getPetTypeTree();
    },
    //8.点击新增按钮弹出对话框
    handleAdd: function () {
      this.title = "新增";
      this.saveFormVisible = true;
      this.saveForm = {
        id: null,
        name: '',
        description: null,
        parentId: null
      };
      this.getPetTypeTree();
    },
    //9.新增或修改数据提交到后端
    saveSubmit: function () {
      this.$refs.saveForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.saveLoading = true;
            let para = Object.assign({}, this.saveForm);
            var isArr = para.typeId;
            if (Array.isArray(isArr)){
              if(isArr.length == 0){
                para.typeId = null;
              }else {
                para.typeId = isArr[isArr.length-1]
              }
            }
            this.$http.put("/petType", para).then(res => {
              this.saveLoading = false;//关闭加载框
              this.saveFormVisible = false;//关闭对话框
              if (res.data.success) { //操作成功
                this.getpetTypes();
              } else { //操作失败
                this.$message.error("系统繁忙，请稍后重试!!![500]"); //后端500错误走这里
                this.saveLoading = false;//关闭加载框
                this.saveFormVisible = false;//关闭对话框
              }
            }).catch(res => {
              this.$message.error("系统繁忙，请稍后重试!!![400,404]");
              this.saveLoading = false;//关闭加载框
              this.saveFormVisible = false;//关闭对话框
            })
          });
        }
      });
    },
    //10.获取宠物类型树
    getPetTypeTree(){
      this.$http.get("/petType/petTypeTree").then(res=>{
        this.petTypeTree = res.data;
      })
    }

  },
  mounted() {
    this.getpetTypes();
  }
}
</script>

<style scoped>

</style>